'use strict';

const fs = require('fs')
const util = require('util')
const path = require('path')
const readFilePromise = util.promisify(fs.readFile)
const Controller = require('egg').Controller;

class HomeController extends Controller {
  async index() {
    const { ctx } = this;
    ctx.response.type = 'html';
    let page = await readFilePromise(path.resolve(__dirname, '../public/index.html'));
    ctx.body = page;
  }

  async init() {
    const ctx = this.ctx;
    const title = ctx.request.body.title.replace('|','');
    ctx.session.title = title;
    this.ctx.body = title;
  }

  async like() {
    const { ctx } = this;
    const { name } = ctx.request.body;
    const title = ctx.session.title;
    this.logger.debug("%s 喜欢 %s", title, name);
    await this.service.name.vote(name, title, 1);
    this.ctx.body = await this.service.name.random();
  }

  async dislike() {
    const { ctx } = this;
    const { name } = ctx.request.body;
    const title = ctx.session.title;
    this.logger.debug("%s 不喜欢 %s", title, name);
    await this.service.name.vote(name, title, -1);
    this.ctx.body = await this.service.name.random();
  }

  async remove() {
    const { ctx } = this;
    const { char } = ctx.request.body;
    const title = ctx.session.title;
    await this.service.name.remove(char, title);
    this.ctx.body = await this.service.name.getRemainCount();
  }

  async next() {
    this.ctx.body = await this.service.name.random();
  }

  async ranks() {
    const ranks = await this.service.name.getRanks();
    const items = [];
    for(let i=0;i<ranks.length;i++) {
      items.push({
        rank: i + 1,
        name: ranks[i].name,
        vote: ranks[i].vote,
        person: await this.service.name.getPersons(ranks[i].name)
      });
    }
    this.ctx.body = {
      ranks: items
    };
  }
}

module.exports = HomeController;
